package com.qf.system.param.controller;

import java.io.PrintWriter;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.qf.system.menu.model.Menu;
import com.qf.system.param.model.Param;
import com.qf.system.param.service.ParamService;
import com.qf.util.AppUtil;
import com.qf.util.PageData;
import com.qf.util.PropertyReader;
import com.qf.util.common.Const;
import com.qf.util.controller.BaseController;
/** 
 * 类名称：ParamController
 * 创建人：周广文
 * 创建时间：2015-06-02
 */
@Controller
@RequestMapping(value="/qjqwmain/param")
public class ParamController extends BaseController{
	@Resource(name="paramService")
	private ParamService paramService;
	/**
	 * 新增
	 */
	@RequestMapping(value="/save")
	public ModelAndView save(@Validated @ModelAttribute("param") Param param,Errors errors ) throws Exception{
		logBefore(logger, "新增Param");
		ModelAndView mv = this.getModelAndView();
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		
		if(errors.hasErrors()){
			 mv.setViewName("/WEB-INF/system/error/error_all");
	            return mv;  
		}else{
			param.setOperTime(new Date());
			param.setOperUser(session.getAttribute(Const.SESSION_USERNAME).toString());
			int i=paramService.save(param);
			if(i>0){
				mv.addObject("msg","success");
				mv.setViewName("save_result");
				return mv;
			}else{
				mv.addObject("msg","error");
				mv.setViewName("save_result");
				return mv;
			}
		}
	}
	/**
	 * 删除
	 */
	@RequestMapping(value="/delete")
	public void delete(@NotNull String PARAM_ID, PrintWriter out){
		logBefore(logger, "删除Param");
		try{
		   int i=paramService.delete(PARAM_ID);
		   if(i>0){
			out.write("success");
			out.close();
		   }else{
			   out.write("error");
				out.close();
		   }
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}
	
	/**
	 * 修改
	 */
	@RequestMapping(value="/edit")
	public ModelAndView edit(@Validated @ModelAttribute("param") Param param ,Errors errors) throws Exception{
		logBefore(logger, "修改Param");
		ModelAndView mv = this.getModelAndView();
		if(errors.hasErrors()){
			 mv.setViewName("/WEB-INF/system/error/error_all");
	            return mv;  
		}else{
		   int i= paramService.edit(param);
		   if(i>0){
		   mv.addObject("msg","success");
		   mv.setViewName("save_result");
		   return mv;
		   }else{
			   mv.addObject("msg","error");
			   mv.setViewName("save_result");
			   return mv;
		   }
		}
	}
	/**
	 * 列表
	 */
	@RequestMapping(value="/list")
	public ModelAndView list(){
		logBefore(logger, "列表Param");
		ModelAndView mv = this.getModelAndView();
		try{
			List<Param>	varList = paramService.list();	//列出Param列表
			this.getHC(); //调用权限
			mv.setViewName("/WEB-INF/system/param/param_list");
			mv.addObject("varList", varList);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	/**
	 * 列表
	 */
	@RequestMapping(value="/param")
	public ModelAndView param(){
		logBefore(logger, "列表Param");
		ModelAndView mv = this.getModelAndView();
		try{
			this.getHC(); //调用权限
			mv.setViewName("/WEB-INF/system/param/param");
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	/**
	 * 去新增页面
	 */
	@RequestMapping(value="/goAdd")
	public ModelAndView goAdd(){
		logBefore(logger, "去新增Param页面");
		ModelAndView mv = this.getModelAndView();
		try {
			mv.setViewName("/WEB-INF/system/param/param_edit");
			mv.addObject("msg", "save");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	/**
	 * 去修改页面
	 */
	@RequestMapping(value="/goEdit")
	public ModelAndView goEdit(@RequestParam String PARAM_ID){
		logBefore(logger, "去修改Param页面");
		ModelAndView mv = this.getModelAndView();
		try {
			Param param =paramService.findById(PARAM_ID);	//根据ID读取
		
			mv.addObject("msg", "edit");
			mv.addObject("params", param);
			mv.setViewName("/WEB-INF/system/param/param_edit");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	/**
	 * 批量删除
	 */
	@RequestMapping(value="/deleteAll")
	@ResponseBody
	public Object deleteAll() {
		logBefore(logger, "批量删除Param");
		PageData pd = new PageData();		
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String DATA_IDS = pd.getString("DATA_IDS");
			if(null != DATA_IDS && !"".equals(DATA_IDS)){
				String ArrayDATA_IDS[] = DATA_IDS.split(",");
				List<Integer> list=new ArrayList<Integer>();
				for(int i=0;i<ArrayDATA_IDS.length;i++){
					list.add(Integer.parseInt(ArrayDATA_IDS[i]));
							
				}
				paramService.deleteAll(list);
				pd.put("msg", "ok");
			}else{
				pd.put("msg", "no");
			}
			pdList.add(pd);
			map.put("list", pdList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	
	@RequestMapping("upparam")
	public void upparam(@RequestParam("key") String key,@RequestParam("values") String values,HttpServletRequest request,HttpServletResponse response){
		try {
			values=URLDecoder.decode(values,"UTF-8");
			PropertyReader.writeData(key, values, Const.CONF);
			System.out.println(PropertyReader.readValue(Const.CONF, key));
			response.getWriter().write("success");
		} catch (Exception e) {
			// TODO: handle exception
			logger.error( e);
		}
	   
		
	}
	
	/* ===============================权限================================== */
	@SuppressWarnings("unchecked")
	public void getHC(){
		ModelAndView mv = this.getModelAndView();
		HttpSession session = this.getRequest().getSession();
		Map<String, String> map = (Map<String, String>)session.getAttribute(Const.SESSION_QX);
		mv.addObject(Const.SESSION_QX,map);	//按钮权限
		List<Menu> menuList = (List<Menu>)session.getAttribute(Const.SESSION_menuList);
		mv.addObject(Const.SESSION_menuList, menuList);//菜单权限
	}
	/* ===============================权限================================== */
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
	}
	/**
	 * 将字符串转成unicode
	 * 
	 * @param str
	 *            待转字符串
	 * @return unicode字符串
	 */
	public static String convert(String str) {
		str = (str == null ? "" : str);
		String tmp;
		StringBuffer sb = new StringBuffer(1000);
		char c;
		int i, j;
		sb.setLength(0);
		for (i = 0; i < str.length(); i++) {
			c = str.charAt(i);
			sb.append("\\u");
			j = (c >>> 8); // 取出高8位
			tmp = Integer.toHexString(j);
			if (tmp.length() == 1)
				sb.append("0");
			sb.append(tmp);
			j = (c & 0xFF); // 取出低8位
			tmp = Integer.toHexString(j);
			if (tmp.length() == 1)
				sb.append("0");
			sb.append(tmp);

		}
		return (new String(sb));
	}
}
